import { delCart, getCartList, updateCartProd } from '@/api/cart'
import { Toast } from 'vant'
// 购物车 vuex
const state = {
  cartList: []
}
const mutations = {
  setCartList (state, newList) {
    state.cartList = newList
  },
  toggleCheck (state, goodsId) {
    const cart = state.cartList.find(item => item.goods_id === goodsId)
    cart.isChecked = !cart.isChecked
  },
  toggleAllCheck (state, isCheckedAll) {
    state.cartList.forEach(item => { item.isChecked = isCheckedAll })
  },
  changeCount (state, obj) {
    const cart = state.cartList.find(item => item.goods_id === obj.goodsId)
    cart.goods_num = obj.value
  }
}
// 异步操作都放在actions里面
const actions = {
  // 异步查询购物车信息
  async getCartListAction (context) {
    const { data } = await getCartList()
    console.log(data)
    // 添加一个是否选中的属性
    data.list.forEach(item => {
      item.isChecked = true
    })
    context.commit('setCartList', data.list)
  },
  async changeCartAction (context, obj) {
    context.commit('changeCount', obj)
    await updateCartProd(obj.goodsId, obj.value, obj.goodsSkuId)
    console.log(obj)
  },
  // 删除购物车
  async delCartAction (context) {
    const cartIds = context.getters.selCartIds
    const res = await delCart(cartIds)
    console.log(res)
    // 删除成功之后，重新拉取购物车数据
    context.dispatch('getCartListAction')
    Toast('购物车商品删除成功')
  }
}
const getters = {
  cartTotal (state) {
    return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
  },
  isAllChecked (state) {
    return state.cartList.every(item => item.isChecked)
  },
  // 选中的商品
  selCartList (state) {
    return state.cartList.filter(item => item.isChecked)
  },
  // 调用getters中其他方法可以用getters.方法名接收
  selPrice (state, getters) {
    return getters.selCartList.reduce((sum, item) => sum + item.goods.goods_price_min * item.goods_num, 0).toFixed(2)
  },
  selCount (state, getters) {
    return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
  },
  selCartIds (state, getters) {
    return getters.selCartList.map(item => item.id)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
